package com.example.game_app.adapter;


import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.example.game_app.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StarListAdapter extends ArrayAdapter<Map<String,String>> {
    private Context context;
    private List<Map<String,String>> starList;

    /**
     * 图片id 和图片的映射
     */
    private static final Map<String, Integer> IMAGE_RESOURCES_MAP = new HashMap<>();

    static{
        IMAGE_RESOURCES_MAP.put("pite", R.drawable.pite);
        IMAGE_RESOURCES_MAP.put("liuyin", R.drawable.liuyin);
        IMAGE_RESOURCES_MAP.put("3mz", R.drawable.mz3);

    }
    public StarListAdapter(@NonNull Context context, List<Map<String,String>> starList) {
        super(context, R.layout.game_star_view, starList);
        this.context = context;
        this.starList = starList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        ViewHolder viewHolder;
        if(convertView==null){
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.game_star_item,parent,false);
            viewHolder = new ViewHolder();

            viewHolder.starName = convertView.findViewById(R.id.starName);
            viewHolder.starIntroduction = convertView.findViewById(R.id.starIntroduction);
            viewHolder.starImage = convertView.findViewById(R.id.starImage);
            convertView.setTag(viewHolder);
        }else{
            viewHolder= (ViewHolder) convertView.getTag();
        }
    //     从getItem方法中获取当前位置的明星数据
        Map<String,String> star = getItem(position);
        if(star!=null){
            viewHolder.starName.setText(star.get("starName"));
            viewHolder.starIntroduction.setText(star.get("starIntroduction"));
            // 根据游戏名称获取对应的图像资源，并设置到图像视图上
            // 获取图片名称
            String starImage = star.get("starImage");
            // 尝试从映射中获取资源ID
            Integer resourceId = IMAGE_RESOURCES_MAP.get(starImage);
            if (resourceId != null) {
                Drawable drawable = ContextCompat.getDrawable(context, resourceId);
                viewHolder.starImage.setImageDrawable(drawable);
            } else {
                // 如果找不到对应的资源，记录错误日志
                Log.e("ImageLoader", "Resource not found for gameImage: " + starImage);
            }
        }
        return convertView;
    }

    static class ViewHolder {
        TextView starName;
        TextView starIntroduction;
        ImageView starImage;
    }
}
